package com.hcg.multiplydatasource.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

//import org.mybatis.spring.annotation.MapperScan;


/**
 * 读取 DataSource 数据源
 */
@Configuration  // 注册到 spring 容器中
// 扫包范围
@MapperScan(basePackages = "com.hcg.multiplydatasource.mapper.hcmapper",sqlSessionFactoryRef = "hcgSqlSessionFactory")
public class HcgDataSourceConfig {

    @Bean(name = "hcgDataSource")
//    @Qualifier("hcgDataSource") // 依赖注入时候的名字
    @ConfigurationProperties(prefix="spring.datasource.hcg") // 扫描application 配置文件时的前缀
//    @Primary
    public DataSource hcgDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "hcgSqlSessionFactory")
//    @Primary
    public SqlSessionFactory hcgSqlSessionFactory(@Qualifier("hcgDataSource") DataSource hcgDataSource) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(hcgDataSource);
        // 加载 mapper 对应的 xml 文件，如果没有可以注释掉
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mappers/hcg/*.xml")
        );
        return bean.getObject();
    }

    @Bean(name = "hcgTransactionManager")
//    @Primary
    public DataSourceTransactionManager hcgTransactionManager(@Qualifier("hcgDataSource") DataSource dataSource) throws Exception{
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "hcgSqlSessionTemplate")
//    @Primary
    public SqlSessionTemplate hcgSqlSessionTemplate(@Qualifier("hcgSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception{
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}